package com.dangf.interceptor;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
/**
 * 拦截器，验证 token
 * @author Hello_海生
 * @date 2014年3月27日
 */
public class TokenInterceptor extends HandlerInterceptorAdapter{
			
	@Override
	public boolean preHandle(HttpServletRequest request,HttpServletResponse response, Object handler) throws Exception {
		//设置 JSON 不使用  循环引用
		JSON.DEFAULT_GENERATE_FEATURE |= SerializerFeature.DisableCircularReferenceDetect.getMask();
		//Format formatter = new SimpleDateFormat("yyyy-MM-dd");
		//String serverKey="DangF+"+formatter.format(new Date())+"+DangF";
		
		//serverKey=getMd5(serverKey);
		
		//System.out.println(serverKey+"请求地址:"+request.getServletPath());
		
		if(request.getParameter("key")==null || "".equals(request.getParameter("key")))return false;
		if(request.getParameter("key").equals("DangF")) return true;
		
		
		
		return false;
		//return super.preHandle(request, response, handler);
	}
	
	
	/**
	 * 获取MD5
	 * @param b
	 * @return
	 * @throws NoSuchAlgorithmException 
	 */
	 @SuppressWarnings("unused")
	private static String getMd5(String key) throws NoSuchAlgorithmException{   
		 MessageDigest md5 = MessageDigest.getInstance("MD5");
		 md5.update((key).getBytes());
		 byte[] b = md5.digest();
	        StringBuffer buf = new StringBuffer();    
	         for(int i = 0; i < b.length; i ++){    
	             int a = b[i];  
	             if(a<0)  
	                 a+=256;  
	             if(a<16)  
	                 buf.append("0");  
	             buf.append(Integer.toHexString(a));  
	            
	         }            
	         return buf.toString();  //32位    
	 }
}
